package net.jltec.utils;

import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.HTTP;

public class WebUtils {

	 
	
	
	public static String doGet(String url,Map<String,String> params) {
		String result = null;
		
		if(params!=null){
			url = UrlUtils.buildUrlByQueryStringMapAndBaseUrl(url, params);
		}
		
		HttpGet getRequest = new HttpGet(url);
		HttpClient httpClient = new DefaultHttpClient();
		HttpResponse response = null;
		try {
			response = httpClient.execute(getRequest);
		} catch (Exception e) {
			e.printStackTrace();
		}
		result = ApacheUtils.parseStringFromEntity(response.getEntity());
		return result;
	}
	
	
	public static String doPost(String url, Map addtionalParams) {
		HttpPost postRequest = new HttpPost(url);
		
		//postRequest.getParams().setParameter("http.protocol.content-charset", AppConfig.ENCODING);
		postRequest.addHeader("charset", HTTP.UTF_8);
		
		
		List<NameValuePair> pairs = ApacheUtils
				.convertMapToNameValuePairs(addtionalParams);
		HttpEntity entity = null;
		HttpResponse response = null;
		try {
			entity = new UrlEncodedFormEntity(pairs,HTTP.UTF_8);
			postRequest.setEntity(entity);
			
			response = new DefaultHttpClient().execute(postRequest);
		} catch (Exception e) {
			e.printStackTrace();
		}
		String result = ApacheUtils.getResponseText(response);
		return result;
	}
	
	 
}
